<!DOCTYPE html>
<html lang="zh-CN">

<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>用户数据管理系统</title>
    <link rel="shortcut icon" href="../../res/logo_main.png" />
    <link href="index.css" type="text/css" rel="stylesheet" />
    <!-- 引入Tailwind CSS -->
    <script src="https://cdn.tailwindcss.com"></script>
    <!-- 引入Font Awesome -->
    <link href="https://cdn.jsdelivr.net/npm/font-awesome@4.7.0/css/font-awesome.min.css" rel="stylesheet">
    <!-- Tailwind配置 -->
    <script>
        tailwind.config = {
            theme: {
                extend: {
                    colors: {
                        primary: '#165DFF',
                        secondary: '#36D399',
                        danger: '#F87272',
                        warning: '#FBBD23',
                        info: '#3ABFF8',
                        dark: '#1E293B',
                        light: '#F8FAFC'
                    },
                    fontFamily: {
                        inter: ['Inter', 'system-ui', 'sans-serif'],
                    },
                },
            }
        }
    </script>
    <!-- 自定义工具类 -->
    <style type="text/tailwindcss">
        @layer utilities {
            .content-auto {
                content-visibility: auto;
            }
            .form-input-focus {
                @apply focus:ring-2 focus:ring-primary/50 focus:border-primary transition duration-200;
            }
            .btn-hover {
                @apply transition-all duration-200 transform hover:scale-[1.02] active:scale-[0.98];
            }
            .register-login-btn {
                @apply px-4 py-2 rounded-lg bg-primary text-white hover:bg-primary/90 transition flex items-center gap-2;
            }
            .table-row-hover {
                @apply hover:bg-gray-50 transition-colors duration-150;
            }
        }
    </style>
</head>

<body class="bg-gray-50 font-inter text-dark">
    <!-- 页眉 -->
    <nav>
        <!-- 页面标题和操作按钮 -->
        <div id="nav-main" class="flex flex-col md:flex-row md:items-center md:justify-between gap-4">
            <div>
                <h2 class="text-[clamp(1.5rem,3vw,2rem)] font-bold text-dark">用户账户管理</h2>
                <p class="text-gray-500 mt-1">管理系统中的所有用户账户信息</p>
            </div>
            <div class="flex flex-wrap gap-3">
                <div class="relative">
                    <input type="text" id="searchInput" placeholder="搜索用户..."
                        class="pl-10 pr-4 py-2 rounded-lg border border-gray-300 focus:outline-none focus:border-primary w-full md:w-64 form-input-focus">
                    <i class="fa fa-search absolute left-3 top-1/2 transform -translate-y-1/2 text-gray-400"></i>
                </div>
            </div>
            <div class="register-login flex items-center gap-2">
                <button id="registerBtn" class="register-login-btn">注册</button>
                <span>丨</span>
                <button id="loginBtn" class="register-login-btn">登录</button>
            </div>
        </div>
    </nav>
    <!-- 主要内容区域 -->
    <main class="container mx-auto px-4 py-8">
        <!-- 用户列表 -->
        <div class="bg-white rounded-xl shadow overflow-hidden">
            <div class="overflow-x-auto">
                <table class="min-w-full divide-y divide-gray-200">
                    <thead class="bg-gray-50">
                        <tr>
                            <th scope="col"
                                class="px-6 py-3 text-left text-xs font-medium text-gray-500 uppercase tracking-wider">
                                ID
                            </th>
                            <th scope="col"
                                class="px-6 py-3 text-left text-xs font-medium text-gray-500 uppercase tracking-wider">
                                用户名
                            </th>
                            <th scope="col"
                                class="px-6 py-3 text-left text-xs font-medium text-gray-500 uppercase tracking-wider">
                                邮箱
                            </th>
                            <th scope="col"
                                class="px-6 py-3 text-right text-xs font-medium text-gray-500 uppercase tracking-wider">
                                操作
                            </th>
                        </tr>
                    </thead>
                    <tbody class="bg-white divide-y divide-gray-200" id="userList">
                        <tr class="text-center">
                            <td colspan="4" class="px-6 py-12 text-gray-500">
                                <div class="flex flex-col items-center">
                                    <i class="fa fa-folder-open-o text-4xl mb-3 text-gray-300"></i>
                                    <p>暂无用户数据</p>
                                </div>
                            </td>
                        </tr>
                    </tbody>
                </table>
            </div>
            <!-- 分页控件 -->
            <div class="px-6 py-4 border-t border-gray-200">
                <p class="text-sm text-gray-700">
                    共 <span class="font-medium" id="totalUsers">0</span> 条记录
                </p>
            </div>
        </div>
    </main>

    <!-- 认证模块JavaScript -->
    <script>
            (function () {
                let registerModal, loginModal, editModal, registerModalContent, loginModalContent, editModalContent, notification;
                let registerForm, loginForm, editForm;
                let userNameLink = null;

                let callbacks = {
                    onRegisterSuccess: null,
                    onLoginSuccess: null,
                    onAutoLogin: null
                };

                let db;
                const DB_NAME = 'userDB';
                const STORE_NAME = 'users';

                function openDatabase() {
                    return new Promise((resolve, reject) => {
                        const request = indexedDB.open(DB_NAME, 1);
                        request.onupgradeneeded = (event) => {
                            db = event.target.result;
                            const objectStore = db.createObjectStore(STORE_NAME, { keyPath: 'email' });
                            objectStore.createIndex('username', 'username', { unique: true });
                            objectStore.createIndex('password', 'password', { unique: false });
                        };
                        request.onsuccess = (event) => {
                            db = event.target.result;
                            resolve(db);
                        };
                        request.onerror = (event) => {
                            reject(`数据库错误: ${event.target.errorCode}`);
                        };
                    });
                }

                function addUser(user) {
                    return new Promise((resolve, reject) => {
                        const transaction = db.transaction([STORE_NAME], 'readwrite');
                        const objectStore = transaction.objectStore(STORE_NAME);
                        const request = objectStore.add(user);
                        request.onsuccess = () => resolve();
                        request.onerror = (event) => {
                            if (event.target.error.name === 'ConstraintError') {
                                reject('用户名或邮箱已被注册');
                            } else {
                                reject(`注册失败: ${event.target.error}`);
                            }
                        };
                    });
                }

                function getUserByEmail(email) {
                    return new Promise((resolve, reject) => {
                        const transaction = db.transaction([STORE_NAME], 'readonly');
                        const objectStore = transaction.objectStore(STORE_NAME);
                        const request = objectStore.get(email);
                        request.onsuccess = () => resolve(request.result);
                        request.onerror = () => reject(`查找用户失败`);
                    });
                }

                function getUserByUsername(username) {
                    return new Promise((resolve, reject) => {
                        const transaction = db.transaction([STORE_NAME], 'readonly');
                        const objectStore = transaction.objectStore(STORE_NAME);
                        const index = objectStore.index('username');
                        const request = index.get(username);
                        request.onsuccess = () => resolve(request.result);
                        request.onerror = () => reject(`查找用户失败`);
                    });
                }

                function updateUser(user) {
                    return new Promise((resolve, reject) => {
                        const transaction = db.transaction([STORE_NAME], 'readwrite');
                        const objectStore = transaction.objectStore(STORE_NAME);
                        const request = objectStore.put(user);
                        request.onsuccess = () => resolve();
                        request.onerror = (event) => reject(`更新用户失败: ${event.target.error}`);
                    });
                }

                function createModalElements() {
                    const fragment = document.createDocumentFragment();

                    registerModal = document.createElement('div');
                    registerModal.id = 'registerModal';
                    registerModal.className = 'fixed inset-0 bg-black/50 z-50 flex items-center justify-center hidden';
                    registerModal.innerHTML = `
                    <div class="bg-white rounded-xl shadow-2xl w-full max-w-md mx-4 transform transition-all scale-95 opacity-0" id="registerModalContent">
                        <div class="p-6">
                            <div class="flex justify-between items-center mb-4">
                                <h3 class="text-xl font-bold text-dark" id="registerModalTitle">创建账户</h3>
                                <button id="closeRegisterModal" class="text-gray-500 hover:text-gray-700 transition">
                                    <i class="fa fa-times text-xl"></i>
                                </button>
                            </div>
                            <form id="registerForm" class="space-y-4">
                                <div>
                                    <label for="regUsername" class="block text-sm font-medium text-gray-700 mb-1">用户名</label>
                                    <div class="relative">
                                        <span class="absolute inset-y-0 left-0 flex items-center pl-3 text-gray-500">
                                            <i class="fa fa-user"></i>
                                        </span>
                                        <input type="text" id="regUsername" name="regUsername" 
                                            class="pl-10 w-full rounded-lg border border-gray-300 py-2.5 px-4 focus:outline-none form-input-focus"
                                            placeholder="请输入用户名" required>
                                    </div>
                                </div>
                                <div>
                                    <label for="regEmail" class="block text-sm font-medium text-gray-700 mb-1">邮箱</label>
                                    <div class="relative">
                                        <span class="absolute inset-y-0 left-0 flex items-center pl-3 text-gray-500">
                                            <i class="fa fa-envelope"></i>
                                        </span>
                                        <input type="email" id="regEmail" name="regEmail" 
                                            class="pl-10 w-full rounded-lg border border-gray-300 py-2.5 px-4 focus:outline-none form-input-focus"
                                            placeholder="请输入邮箱" required>
                                    </div>
                                </div>
                                <div>
                                    <label for="regPassword" class="block text-sm font-medium text-gray-700 mb-1">密码</label>
                                    <div class="relative">
                                        <span class="absolute inset-y-0 left-0 flex items-center pl-3 text-gray-500">
                                            <i class="fa fa-lock"></i>
                                        </span>
                                        <input type="password" id="regPassword" name="regPassword" 
                                            class="pl-10 w-full rounded-lg border border-gray-300 py-2.5 px-4 focus:outline-none form-input-focus"
                                            placeholder="请输入密码" required>
                                    </div>
                                </div>
                                <div>
                                    <button type="submit" 
                                        class="w-full bg-primary hover:bg-primary/90 text-white font-medium py-2.5 px-4 rounded-lg btn-hover" id="registerSubmitBtn">
                                        注册账户
                                    </button>
                                </div>
                            </form>
                            <div class="mt-4 text-center text-sm text-gray-600">
                                <span id="registerModalHint">已有账户?</span>
                                <button id="switchToLogin" class="text-primary hover:underline">立即登录</button>
                            </div>
                        </div>
                    </div>
                `;
                    fragment.appendChild(registerModal);

                    loginModal = document.createElement('div');
                    loginModal.id = 'loginModal';
                    loginModal.className = 'fixed inset-0 bg-black/50 z-50 flex items-center justify-center hidden';
                    loginModal.innerHTML = `
                    <div class="bg-white rounded-xl shadow-2xl w-full max-w-md mx-4 transform transition-all scale-95 opacity-0" id="loginModalContent">
                        <div class="p-6">
                            <div class="flex justify-between items-center mb-4">
                                <h3 class="text-xl font-bold text-dark">登录账户</h3>
                                <button id="closeLoginModal" class="text-gray-500 hover:text-gray-700 transition">
                                    <i class="fa fa-times text-xl"></i>
                                </button>
                            </div>
                            <form id="loginForm" class="space-y-4">
                                <div>
                                    <label for="loginIdentifier" class="block text-sm font-medium text-gray-700 mb-1">用户名或邮箱</label>
                                    <div class="relative">
                                        <span class="absolute inset-y-0 left-0 flex items-center pl-3 text-gray-500">
                                            <i class="fa fa-user"></i>
                                        </span>
                                        <input type="text" id="loginIdentifier" name="loginIdentifier" 
                                            class="pl-10 w-full rounded-lg border border-gray-300 py-2.5 px-4 focus:outline-none form-input-focus"
                                            placeholder="请输入用户名或邮箱" required>
                                    </div>
                                </div>
                                <div>
                                    <label for="loginPassword" class="block text-sm font-medium text-gray-700 mb-1">密码</label>
                                    <div class="relative">
                                        <span class="absolute inset-y-0 left-0 flex items-center pl-3 text-gray-500">
                                            <i class="fa fa-lock"></i>
                                        </span>
                                        <input type="password" id="loginPassword" name="loginPassword" 
                                            class="pl-10 w-full rounded-lg border border-gray-300 py-2.5 px-4 focus:outline-none form-input-focus"
                                            placeholder="请输入密码" required>
                                    </div>
                                </div>
                                <div class="flex items-center justify-between">
                                    <div class="flex items-center">
                                        <input id="rememberMe" type="checkbox" class="h-4 w-4 text-primary focus:ring-primary border-gray-300 rounded">
                                        <label for="rememberMe" class="ml-2 block text-sm text-gray-700">记住我</label>
                                    </div>
                                    <div class="text-sm">
                                        <a href="../admin_entrance_page/index.html" class="text-primary hover:underline">若忘记密码,请联系管理员</a>
                                    </div>
                                </div>
                                <div>
                                    <button type="submit" 
                                        class="w-full bg-primary hover:bg-primary/90 text-white font-medium py-2.5 px-4 rounded-lg btn-hover">
                                        登录
                                    </button>
                                </div>
                            </form>
                            <div class="mt-4 text-center text-sm text-gray-600">
                                还没有账户? <button id="switchToRegister" class="text-primary hover:underline">立即注册</button>
                            </div>
                        </div>
                    </div>
                `;
                    fragment.appendChild(loginModal);

                    editModal = document.createElement('div');
                    editModal.id = 'editModal';
                    editModal.className = 'fixed inset-0 bg-black/50 z-50 flex items-center justify-center hidden';
                    editModal.innerHTML = `
                    <div class="bg-white rounded-xl shadow-2xl w-full max-w-md mx-4 transform transition-all scale-95 opacity-0" id="editModalContent">
                        <div class="p-6">
                            <div class="flex justify-between items-center mb-4">
                                <h3 class="text-xl font-bold text-dark">编辑用户</h3>
                                <button id="closeEditModal" class="text-gray-500 hover:text-gray-700 transition">
                                    <i class="fa fa-times text-xl"></i>
                                </button>
                            </div>
                            <form id="editForm" class="space-y-4">
                                <div>
                                    <label for="editUsername" class="block text-sm font-medium text-gray-700 mb-1">用户名</label>
                                    <div class="relative">
                                        <span class="absolute inset-y-0 left-0 flex items-center pl-3 text-gray-500">
                                            <i class="fa fa-user"></i>
                                        </span>
                                        <input type="text" id="editUsername" name="editUsername" 
                                            class="pl-10 w-full rounded-lg border border-gray-300 py-2.5 px-4 focus:outline-none form-input-focus"
                                            placeholder="请输入用户名" required>
                                    </div>
                                </div>
                                <div>
                                    <label for="editEmail" class="block text-sm font-medium text-gray-700 mb-1">邮箱</label>
                                    <div class="relative">
                                        <span class="absolute inset-y-0 left-0 flex items-center pl-3 text-gray-500">
                                            <i class="fa fa-envelope"></i>
                                        </span>
                                        <input type="email" id="editEmail" name="editEmail" 
                                            class="pl-10 w-full rounded-lg border border-gray-300 py-2.5 px-4 focus:outline-none form-input-focus"
                                            placeholder="请输入邮箱" required>
                                    </div>
                                </div>
                                <div>
                                    <label for="editPassword" class="block text-sm font-medium text-gray-700 mb-1">密码</label>
                                    <div class="relative">
                                        <span class="absolute inset-y-0 left-0 flex items-center pl-3 text-gray-500">
                                            <i class="fa fa-lock"></i>
                                        </span>
                                        <input type="password" id="editPassword" name="editPassword" 
                                            class="pl-10 w-full rounded-lg border border-gray-300 py-2.5 px-4 focus:outline-none form-input-focus"
                                            placeholder="留空保持原密码">
                                    </div>
                                </div>
                                <div>
                                    <button type="submit" 
                                        class="w-full bg-primary hover:bg-primary/90 text-white font-medium py-2.5 px-4 rounded-lg btn-hover">
                                        保存修改
                                    </button>
                                </div>
                            </form>
                        </div>
                    </div>
                `;
                    fragment.appendChild(editModal);

                    notification = document.createElement('div');
                    notification.id = 'notification';
                    notification.className = 'fixed bottom-4 right-4 bg-white rounded-lg shadow-lg p-4 transform translate-y-10 opacity-0 transition-all duration-300 z-50 max-w-xs';
                    notification.innerHTML = `
                    <div class="flex items-start">
                        <div id="notificationIcon" class="flex-shrink-0 mt-0.5">
                            <i class="fa fa-info-circle text-blue-500 text-xl"></i>
                        </div>
                        <div class="ml-3">
                            <h3 id="notificationTitle" class="text-sm font-medium text-gray-800">通知标题</h3>
                            <div id="notificationMessage" class="mt-1 text-sm text-gray-600">通知内容将显示在这里...</div>
                        </div>
                        <button id="closeNotification" class="ml-auto flex-shrink-0 text-gray-400 hover:text-gray-600">
                            <i class="fa fa-times"></i>
                        </button>
                    </div>
                `;
                    fragment.appendChild(notification);

                    document.body.appendChild(fragment);

                    registerModalContent = document.getElementById('registerModalContent');
                    loginModalContent = document.getElementById('loginModalContent');
                    editModalContent = document.getElementById('editModalContent');
                    registerForm = document.getElementById('registerForm');
                    loginForm = document.getElementById('loginForm');
                    editForm = document.getElementById('editForm');
                }

                function animateModal(modal, content, show = true) {
                    if (show) {
                        modal.classList.remove('hidden');
                        setTimeout(() => {
                            content.classList.remove('scale-95', 'opacity-0');
                            content.classList.add('scale-100', 'opacity-100');
                        }, 10);
                    } else {
                        content.classList.remove('scale-100', 'opacity-100');
                        content.classList.add('scale-95', 'opacity-0');
                        setTimeout(() => {
                            modal.classList.add('hidden');
                        }, 300);
                    }
                }

                function showNotification(title, message, type = 'info') {
                    const notificationEl = document.getElementById('notification');
                    const notificationTitle = document.getElementById('notificationTitle');
                    const notificationMessage = document.getElementById('notificationMessage');
                    const notificationIcon = document.getElementById('notificationIcon').querySelector('i');

                    notificationTitle.textContent = title;
                    notificationMessage.textContent = message;
                    notificationIcon.className = 'fa ';
                    if (type === 'success') {
                        notificationIcon.className += 'fa-check-circle text-green-500 text-xl';
                    } else if (type === 'error') {
                        notificationIcon.className += 'fa-exclamation-circle text-red-500 text-xl';
                    } else if (type === 'warning') {
                        notificationIcon.className += 'fa-exclamation-triangle text-yellow-500 text-xl';
                    } else {
                        notificationIcon.className += 'fa-info-circle text-blue-500 text-xl';
                    }
                    notificationEl.classList.remove('translate-y-10', 'opacity-0');
                    notificationEl.classList.add('translate-y-0', 'opacity-100');
                    setTimeout(() => {
                        hideNotification();
                    }, 3000);
                }

                function hideNotification() {
                    const notificationEl = document.getElementById('notification');
                    notificationEl.classList.remove('translate-y-0', 'opacity-100');
                    notificationEl.classList.add('translate-y-10', 'opacity-0');
                }

                function createUserNameLink(username) {
                    if (userNameLink) {
                        userNameLink.remove();
                    }
                    userNameLink = document.createElement('button');
                    userNameLink.id = 'userNameLink';
                    userNameLink.className = 'register-login-btn';
                    userNameLink.textContent = `Hi, ${username}`;
                    userNameLink.addEventListener('click', () => {
                        const confirmLogout = confirm('确定要退出登录吗？');
                        if (confirmLogout) {
                            logoutHandler();
                        }
                    });
                    const container = document.querySelector('.register-login');
                    if (container) {
                        const originalButtons = container.querySelectorAll('button');
                        originalButtons.forEach(btn => {
                            if (btn.id !== 'userNameLink') {
                                btn.remove();
                            }
                        });
                        container.appendChild(userNameLink);
                    }
                }

                function logoutHandler() {
                    const container = document.querySelector('.register-login');
                    if (container) {
                        if (userNameLink) {
                            userNameLink.remove();
                            userNameLink = null;
                        }
                        const registerBtn = document.createElement('button');
                        registerBtn.id = 'registerBtn';
                        registerBtn.className = 'register-login-btn';
                        registerBtn.textContent = '注册';
                        registerBtn.onclick = openRegisterModal;
                        const separator = document.createElement('span');
                        separator.textContent = '丨';
                        const loginBtn = document.createElement('button');
                        loginBtn.id = 'loginBtn';
                        loginBtn.className = 'register-login-btn';
                        loginBtn.textContent = '登录';
                        loginBtn.onclick = openLoginModal;
                        container.appendChild(registerBtn);
                        container.appendChild(separator);
                        container.appendChild(loginBtn);
                    }
                    localStorage.removeItem('currentUser');
                    showNotification('成功', '已退出登录', 'success');
                }

                function checkLoginStatus() {
                    const userData = localStorage.getItem('currentUser');
                    if (userData) {
                        try {
                            const user = JSON.parse(userData);
                            createUserNameLink(user.username);
                            if (typeof callbacks.onAutoLogin === 'function') {
                                callbacks.onAutoLogin(user);
                            }
                            return true;
                        } catch (error) {
                            console.error('解析用户数据失败:', error);
                            return false;
                        }
                    }
                    return false;
                }

                function initEventListeners() {
                    document.getElementById('closeRegisterModal').addEventListener('click', () => {
                        animateModal(registerModal, registerModalContent, false);
                    });
                    document.getElementById('closeLoginModal').addEventListener('click', () => {
                        animateModal(loginModal, loginModalContent, false);
                    });
                    document.getElementById('closeEditModal').addEventListener('click', () => {
                        animateModal(editModal, editModalContent, false);
                    });
                    document.getElementById('switchToLogin').addEventListener('click', () => {
                        animateModal(registerModal, registerModalContent, false);
                        setTimeout(() => {
                            animateModal(loginModal, loginModalContent, true);
                        }, 300);
                    });
                    document.getElementById('switchToRegister').addEventListener('click', () => {
                        animateModal(loginModal, loginModalContent, false);
                        setTimeout(() => {
                            animateModal(registerModal, registerModalContent, true);
                        }, 300);
                    });
                    registerModal.addEventListener('click', (e) => {
                        if (e.target === registerModal) {
                            animateModal(registerModal, registerModalContent, false);
                        }
                    });
                    loginModal.addEventListener('click', (e) => {
                        if (e.target === loginModal) {
                            animateModal(loginModal, loginModalContent, false);
                        }
                    });
                    editModal.addEventListener('click', (e) => {
                        if (e.target === editModal) {
                            animateModal(editModal, editModalContent, false);
                        }
                    });
                    document.getElementById('closeNotification').addEventListener('click', hideNotification);

                    registerForm.addEventListener('submit', async (e) => {
                        e.preventDefault();
                        const username = document.getElementById('regUsername').value.trim();
                        const email = document.getElementById('regEmail').value.trim();
                        const password = document.getElementById('regPassword').value;
                        if (!username || !email || !password) {
                            showNotification('错误', '请填写所有必填字段', 'error');
                            return;
                        }
                        const emailRegex = /^[^\s@]+@[^\s@]+\.[^\s@]+$/;
                        if (!emailRegex.test(email)) {
                            showNotification('错误', '请输入有效的邮箱地址', 'error');
                            return;
                        }
                        if (password.length < 6) {
                            showNotification('错误', '密码长度至少需要6个字符', 'error');
                            return;
                        }
                        try {
                            const userByEmail = await getUserByEmail(email);
                            if (userByEmail) {
                                showNotification('错误', '该邮箱已被注册', 'error');
                                return;
                            }
                            const userByUsername = await getUserByUsername(username);
                            if (userByUsername) {
                                showNotification('错误', '该用户名已被使用', 'error');
                                return;
                            }
                            const newUser = {
                                username,
                                email,
                                password,
                                createdAt: new Date().toISOString()
                            };
                            await addUser(newUser);
                            showNotification('成功', '注册成功，请登录', 'success');
                            registerForm.reset();
                            animateModal(registerModal, registerModalContent, false);
                            setTimeout(() => {
                                animateModal(loginModal, loginModalContent, true);
                            }, 300);
                            if (typeof callbacks.onRegisterSuccess === 'function') {
                                callbacks.onRegisterSuccess(newUser);
                            }
                        } catch (error) {
                            showNotification('错误', error, 'error');
                            console.error('注册失败:', error);
                        }
                    });

                    loginForm.addEventListener('submit', async (e) => {
                        e.preventDefault();
                        const identifier = document.getElementById('loginIdentifier').value.trim();
                        const password = document.getElementById('loginPassword').value;
                        const rememberMe = document.getElementById('rememberMe').checked;
                        if (!identifier || !password) {
                            showNotification('错误', '请填写所有必填字段', 'error');
                            return;
                        }
                        try {
                            let user;
                            if (identifier.includes('@')) {
                                user = await getUserByEmail(identifier);
                            } else {
                                user = await getUserByUsername(identifier);
                            }
                            if (!user) {
                                showNotification('错误', '用户不存在', 'error');
                                return;
                            }
                            if (user.password !== password) {
                                showNotification('错误', '密码不正确', 'error');
                                return;
                            }
                            showNotification('成功', `欢迎回来，${user.username}！`, 'success');
                            loginForm.reset();
                            animateModal(loginModal, loginModalContent, false);
                            if (rememberMe) {
                                localStorage.setItem('currentUser', JSON.stringify({
                                    username: user.username,
                                    email: user.email
                                }));
                            }
                            if (typeof callbacks.onLoginSuccess === 'function') {
                                callbacks.onLoginSuccess(user);
                            }
                            createUserNameLink(user.username);
                        } catch (error) {
                            showNotification('错误', '登录失败，请稍后再试', 'error');
                            console.error('登录错误:', error);
                        }
                    });

                    editForm.addEventListener('submit', async (e) => {
                        e.preventDefault();
                        const username = document.getElementById('editUsername').value.trim();
                        const email = document.getElementById('editEmail').value.trim();
                        const password = document.getElementById('editPassword').value;
                        const originalEmail = editForm.dataset.originalEmail;
                        if (!username || !email) {
                            showNotification('错误', '请填写所有必填字段', 'error');
                            return;
                        }
                        const emailRegex = /^[^\s@]+@[^\s@]+\.[^\s@]+$/;
                        if (!emailRegex.test(email)) {
                            showNotification('错误', '请输入有效的邮箱地址', 'error');
                            return;
                        }
                        if (password && password.length < 6) {
                            showNotification('错误', '密码长度至少需要6个字符', 'error');
                            return;
                        }
                        try {
                            const originalUser = await getUserByEmail(originalEmail);
                            if (email !== originalEmail) {
                                const userByEmail = await getUserByEmail(email);
                                if (userByEmail) {
                                    showNotification('错误', '该邮箱已被注册', 'error');
                                    return;
                                }
                            }
                            const userByUsername = await getUserByUsername(username);
                            if (userByUsername && userByUsername.email !== originalEmail) {
                                showNotification('错误', '该用户名已被使用', 'error');
                                return;
                            }
                            const updatedUser = {
                                ...originalUser,
                                username,
                                email,
                                password: password || originalUser.password,
                                updatedAt: new Date().toISOString()
                            };
                            await updateUser(updatedUser);
                            showNotification('成功', '用户信息已更新', 'success');
                            editForm.reset();
                            animateModal(editModal, editModalContent, false);
                            await loadUserList();
                        } catch (error) {
                            showNotification('错误', error, 'error');
                            console.error('更新用户失败:', error);
                        }
                    });
                }

                async function loadUserList() {
                    try {
                        const db = await openDatabase();
                        const transaction = db.transaction([STORE_NAME], 'readonly');
                        const objectStore = transaction.objectStore(STORE_NAME);
                        const users = [];
                        await new Promise((resolve) => {
                            objectStore.openCursor().onsuccess = (event) => {
                                const cursor = event.target.result;
                                if (cursor) {
                                    users.push({
                                        id: cursor.key,
                                        username: cursor.value.username,
                                        email: cursor.value.email,
                                        createdAt: cursor.value.createdAt
                                    });
                                    cursor.continue();
                                } else {
                                    resolve();
                                }
                            };
                        });
                        const searchTerm = document.getElementById('searchInput').value.toLowerCase().trim();
                        const filteredUsers = users.filter(user =>
                            user.username.toLowerCase().includes(searchTerm) ||
                            user.email.toLowerCase().includes(searchTerm)
                        );
                        renderUserList(filteredUsers);
                        document.getElementById('totalUsers').textContent = filteredUsers.length;
                    } catch (error) {
                        console.error('加载用户列表失败:', error);
                    }
                }

                function renderUserList(users) {
                    const userList = document.getElementById('userList');
                    userList.innerHTML = '';
                    if (users.length === 0) {
                        userList.innerHTML = `
                        <tr class="text-center">
                            <td colspan="4" class="px-6 py-12 text-gray-500">
                                <div class="flex flex-col items-center">
                                    <i class="fa fa-folder-open-o text-4xl mb-3 text-gray-300"></i>
                                    <p>暂无用户数据</p>
                                </div>
                            </td>
                        </tr>
                    `;
                        return;
                    }
                    users.forEach((user, index) => {
                        const row = document.createElement('tr');
                        row.innerHTML = `
                        <td class="px-6 py-4 whitespace-nowrap text-sm text-gray-500">${index + 1}</td>
                        <td class="px-6 py-4 whitespace-nowrap">
                            <div class="flex items-center">
                                <div class="flex-shrink-0 h-10 w-10 rounded-full bg-primary/10 flex items-center justify-center">
                                    <span class="text-primary font-medium">${user.username.charAt(0).toUpperCase()}</span>
                                </div>
                                <div class="ml-4">${user.username}</div>
                            </div>
                        </td>
                        <td class="px-6 py-4 whitespace-nowrap text-sm text-gray-500">${user.email}</td>
                        <td class="px-6 py-4 whitespace-nowrap text-right text-sm font-medium">
                            <button onclick="window.authModule.openEditModal('${user.email}')" class="text-primary hover:text-primary/80 mr-3">编辑</button>
                            <button onclick="window.deleteUser('${user.email}')" class="text-danger hover:text-danger/80">删除</button>
                        </td>
                    `;
                        userList.appendChild(row);
                    });
                }

                window.authModule = {
                    openEditModal: async function (email) {
                        try {
                            const user = await getUserByEmail(email);
                            if (!user) {
                                showNotification('错误', '用户不存在', 'error');
                                return;
                            }
                            editForm.dataset.originalEmail = user.email;
                            document.getElementById('editUsername').value = user.username;
                            document.getElementById('editEmail').value = user.email;
                            document.getElementById('editPassword').value = '';
                            animateModal(editModal, editModalContent, true);
                        } catch (error) {
                            showNotification('错误', '加载用户信息失败', 'error');
                            console.error('编辑用户失败:', error);
                        }
                    }
                };

                window.deleteUser = async function (email) {
                    if (!confirm('确定要删除此用户吗？')) {
                        return;
                    }
                    try {
                        const db = await openDatabase();
                        const transaction = db.transaction([STORE_NAME], 'readwrite');
                        const objectStore = transaction.objectStore(STORE_NAME);
                        await new Promise((resolve, reject) => {
                            const request = objectStore.delete(email);
                            request.onsuccess = resolve;
                            request.onerror = reject;
                        });
                        showNotification('成功', '用户已删除', 'success');
                        await loadUserList();
                    } catch (error) {
                        showNotification('错误', '删除失败', 'error');
                        console.error('删除用户失败:', error);
                    }
                }

                window.initAuthModal = async function (options = {}) {
                    callbacks = {
                        onRegisterSuccess: options.onRegisterSuccess,
                        onLoginSuccess: (user) => {
                            if (typeof options.onLoginSuccess === 'function') {
                                options.onLoginSuccess(user);
                            }
                            createUserNameLink(user.username);
                        },
                        onAutoLogin: options.onAutoLogin
                    };
                    try {
                        createModalElements();
                        await openDatabase();
                        console.log('数据库已成功初始化');
                        initEventListeners();
                        const isLoggedIn = checkLoginStatus();
                        console.log('用户登录状态:', isLoggedIn ? '已登录' : '未登录');
                        document.getElementById('searchInput').addEventListener('input', debounce(loadUserList, 300));
                        await loadUserList();
                    } catch (error) {
                        console.error('初始化认证弹窗失败:', error);
                    }
                };

                window.openRegisterModal = function () {
                    registerForm.reset();
                    delete registerForm.dataset.editMode;
                    delete registerForm.dataset.email;
                    document.getElementById('registerModalTitle').textContent = '创建账户';
                    document.getElementById('registerSubmitBtn').textContent = '注册账户';
                    document.getElementById('registerModalHint').textContent = '已有账户?';
                    document.getElementById('switchToLogin').style.display = 'inline';
                    animateModal(registerModal, registerModalContent, true);
                };

                window.openLoginModal = function () {
                    animateModal(loginModal, loginModalContent, true);
                };

                function debounce(func, wait) {
                    let timeout;
                    return function () {
                        const context = this;
                        const args = arguments;
                        clearTimeout(timeout);
                        timeout = setTimeout(() => func.apply(context, args), wait);
                    };
                }
            })();

        document.addEventListener('DOMContentLoaded', () => {
            const registerBtn = document.getElementById('registerBtn');
            const loginBtn = document.getElementById('loginBtn');
            if (!registerBtn || !loginBtn) {
                console.error('未找到登录/注册按钮');
                return;
            }
            initAuthModal({
                onRegisterSuccess: (user) => {
                    console.log('用户注册成功:', user);
                },
                onLoginSuccess: (user) => {
                    console.log('用户登录成功:', user);
                },
                onAutoLogin: (user) => {
                    console.log('用户自动登录:', user);
                }
            });
            registerBtn.onclick = openRegisterModal;
            loginBtn.onclick = openLoginModal;
            console.log('认证弹窗初始化完成，按钮事件已绑定');
        });
    </script>
</body>

</html>